package com.badboy.servlet;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.badboy.entity.Users;
import com.badboy.service.UserService;
import com.badboy.util.JsonUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    private UserService userService = new UserService();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型为JSON
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        JSONObject result = new JSONObject();

        try {
            // 读取请求体中的JSON数据
            JSONObject json = JsonUtil.readJson(request);

            String username = json.getString("username");
            String email = json.getString("email");
            String password = json.getString("password");

            // 调用服务层注册用户
            Users user = userService.register(username, email, password);

            // 注册成功
            result.put("success", true);
            result.put("message", "注册成功");
            result.put("user", user);
            result.put("email",  email);
        } catch (Exception e) {
            // 注册失败
            result.put("success", false);
            result.put("message", e.getMessage());
        }

        // 返回JSON响应
        out.print(result.toJSONString());
        out.flush();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}